package com.apes.fn.fico.invoiceApply.model;

import antlr.StringUtils;
import com.apes.fn.fico.expense.ExpenseItem;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.fico.invoiceApply.model
 * @ClassName: InvoiceApply
 * @Author: pyb
 * @Description: 发票申请
 * @CreateTime: 2021-04-08 15:35
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = InvoiceApply.CONST_TABLE_NAME)
public class InvoiceApply extends Model {
    public static final String CONST_TABLE_NAME = "acc_invoice_apply";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "发票申请", padding = 8, prefix = "%(company)")
    @Comment("发票申请单号")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司编码")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "invoice_type", referencedColumnName = "id")
    @Comment("发票类型")
    private Enumeration invoiceType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "invoice_category", referencedColumnName = "id")
    @Comment("发票类别")
    private Enumeration invoiceCategory;

    @Column(name = "email", length = 32)
    @Comment("邮箱")
    private String email;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;

    @States(name = "单据状态", values = {
            @State(id = "sent", name = "制单"),
            @State(id = "apply", name = "申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "accounting", name = "核算"),
            @State(id = "register", name = "登记发票号"),
            @State(id = "done", name = "收回发票"),
    })
    @Column(name = "state", length = 36, nullable = false)
    private String state;


    @Column(name = "total_sale_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售金额合计")
    private double totalSaleAmount = 0;

    @Column(name = "actual_invoiced_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("实际开票金额")
    private double actualInvoicedAmount = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_id", referencedColumnName = "id")
    @Comment("申请人")
    private PartyRole applyId;

    @Column(name = "apply_date")
    @Comment("申请日期")
    private Date applyDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "accounting_id", referencedColumnName = "id")
    @Comment("核算人")
    private PartyRole accountingId;

    @Column(name = "accounting_date")
    @Comment("核算日期")
    private Date accountingDate;

    @Column(name = "remark", length = 128)
    @Comment("备注")
    private String remark;

    @OneToMany(mappedBy = "invoiceApply", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<InvoiceApplyItem> invoiceApplyItems = new ArrayList<>();

    public List<InvoiceApplyItem> getInvoiceApplyItems() {
        for (InvoiceApplyItem invoiceApplyItem : invoiceApplyItems) {
            invoiceApplyItem.setInvoiceApply(this);
        }
        return invoiceApplyItems;
    }

    @Transient
    private List<InvoiceApplyItem> invoiceApplyItemsFilter = new ArrayList<>();
//
//    public List<InvoiceApplyItem> getInvoiceApplyItemsFilter() {
//        List<InvoiceApplyItem> invoiceApplyItemList = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(invoiceApplyItems) && "platformService".equals(this.getInvoiceCategory().getId())){
//            invoiceApplyItemList = getInvoiceApplyItems().stream().filter(f -> f.getProjectFeeDeducted() != 0).collect(Collectors.toList());
//        } else {
//            invoiceApplyItemList = getInvoiceApplyItems();
//        }
//        for (InvoiceApplyItem invoiceApplyItem : invoiceApplyItemList) {
//            invoiceApplyItem.setInvoiceApply(this);
//        }
//        return invoiceApplyItemList;
//    }

    @Transient
    private String actualInvoicedNote;

    public String getActualInvoicedNote() {
        this.actualInvoicedNote =Arith.round(this.actualInvoicedAmount,2)+"(";
        invoiceApplyItems.stream().filter(v-> v.getSalesOrganization() !=null).collect(Collectors.groupingBy(InvoiceApplyItem::getSalesOrganization))
                .forEach((salesOrganization, invoiceApplyItem) -> {
                    double sum = invoiceApplyItem.stream().mapToDouble(InvoiceApplyItem::getPriceTotal).sum();
                    this.actualInvoicedNote+=salesOrganization+" : "+Arith.round( sum,2)+" ; ";
                });
        this.actualInvoicedNote +=")";
        return actualInvoicedNote;
    }

    @Transient
    private String companyName;

    public String getCompanyName() {
        if (company.getParty() == null) return null;
        return company.getParty().getName();
    }

    @Transient
    private String addressAndPhone;

    public String getAddressAndPhone() {
        if (company == null) return null;
        if (company.getParty() == null) return null;
        if (company.getParty().getInvoiceAddress() == null || company.getParty().getInvoicePhone() == null) return "";
        return company.getParty().getInvoiceAddress() + "," + company.getParty().getInvoicePhone();
    }

    @Transient
    private String bankInfo;

    public String getBankInfo() {
        if (company.getParty() == null) return null;
        if (company.getParty().getBankAccount() == null || company.getParty().getBank() == null) return "";
        return company.getParty().getBankAccount() + "," + company.getParty().getBank();
    }

    @Transient
    private String invoiceTitle;

    public String getInvoiceTitle() {
        if (company.getParty() == null) return null;
        if (company.getParty().getInvoiceTitle() == null) return "";
        return company.getParty().getInvoiceTitle();
    }


    @Transient
    private String invoiceTaxNumber;

    public String getInvoiceTaxNumber() {
        if (company.getParty() == null) return null;
        if (company.getParty().getInvoiceNumber() == null) return "";
        return company.getParty().getInvoiceNumber();
    }

    public void computeAmt() {
        double priceTotalSum = 0;
        if (Objects.equals("accessories", invoiceCategory.getId())) {
            priceTotalSum = invoiceApplyItems.stream().mapToDouble(InvoiceApplyItem::getPriceTotal).sum();
            actualInvoicedAmount = priceTotalSum;
        } else {
            priceTotalSum = invoiceApplyItems.stream().mapToDouble(InvoiceApplyItem::getProjectFee).sum();
            actualInvoicedAmount = invoiceApplyItems.stream().mapToDouble(InvoiceApplyItem::getProjectFeeDeducted).sum();
        }
        totalSaleAmount = priceTotalSum;
    }
}
